package com.icangya.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icangya.DAO.ICashRegisterDAO;
import com.icangya.DAO.ICommissionFootDAO;
import com.icangya.Utils.*;
import com.icangya.Value.FootBall;
import com.icangya.Value.StaticValue;
import com.icangya.domain.*;
import com.icangya.service.*;
import com.icangya.weixin.sdk.WXPayUtil;
import com.icangya.wxpay.utils.HttpUtils;
import com.icangya.wxpay.utils.PayUtil;
import com.icangya.wxpay.utils.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.icangya.Value.Error_Code.SUCCESS;

@CrossOrigin
@RestController
@RequestMapping(path = "/foot/user/")
public class UserFootController {

    @Autowired
    private IFootUserService iUserService;

    @Autowired
    private  IAdminUserService iAdminUserService;
    @Autowired
     private  IMoneyService iMoneyService;
    @Autowired
    private  IAgentService iAgentService;
    @Autowired
    private IDomainService iDomainService;
    @Autowired
    private  ICommissionFootDAO iCommissionFootDAO;
    @Autowired
    private  ICashRegisterDAO iCashRegisterDAO;
    @Autowired
    private IFbWxSuitcaseService iFbWxSuitcaseService;
    @Autowired
    private IBadUserService iBadUserService;
    @Autowired
    private  IMissionService iMissionService;

    private  Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 测试用户是否非法登录游戏
     * @param uid
     * @param session
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "loginGame")
    public void loginGame(@RequestParam Long uid,@RequestParam String cy_key,HttpSession session, HttpServletRequest request,
                          HttpServletResponse response) throws Exception {

        String str = "uid=" + uid + "&cy_key=" + StaticValue.SIGN_KEY;//正确的明文
        str = DigestUtils.md5DigestAsHex(str.getBytes("UTF-8"));//第一次md5加密
        String md5Str = DigestUtils.md5DigestAsHex(str.getBytes("UTF-8"));//第二次md5加密
        cy_key = DESUtil.getIstance().decrypt(cy_key, StaticValue.SIGN_KEY).trim();//DES解密 用key
        logger.info(md5Str + "===" + cy_key);
        if (md5Str.equals(cy_key)) {//通过
            User user = iUserService.getUserByUid(uid);
            //request.getSession().setAttribute("Football",user.getOpenId());
            session.removeAttribute(FootBall.FOOT_USER_SESSION);
            session.setAttribute(FootBall.FOOT_USER_SESSION, user);//将登录的用户信息注册进session中


            if(FootBall.MISSION_TURNTABLE==0){
                //获取可领取的奖励
                List<FbMissionAward> missionAwards = iMissionService.getMissionAwardStatus();
                if(missionAwards!=null) {
                    Random random = new Random();
                    int result = random.nextInt(missionAwards.size());
                    FbMissionAward missionAward = missionAwards.get(result);  //获取奖励信息

                    FbTurntableRecord turntableRecord= iMissionService.getTurntableRecordBySystem(0,user.getOpenId());
                    if(turntableRecord==null){
                        //添加转盘记录
                        //String nickName, String openId, long uid, String headImgUrl, long missionId, String missionContent, long awardId, String awardContent, int status
                        FbTurntableRecord fbTurntableRecord=new FbTurntableRecord(user.getNickName(),user.getOpenId(),user.getId(),user.getHeadImgUrl(),0,
                                "赠送体验",missionAward.getId(),missionAward.getAwardContent(),0,new Timestamp(new Date().getTime()));
                        iMissionService.saveFbTurntableRecord(fbTurntableRecord);
                    }

                }
            }



//            session.setMaxInactiveInterval();//设置session存活时间
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append
                    (request.getServletContext().getContextPath()).append("/").toString();
//            response.sendRedirect(tempContextUrl + "footballgame/index.html");//Football.html //跳转到我们的游戏界面  足球小将
            response.sendRedirect("http://"+iDomainService.getDoamin().get(0).getDomainUrl() + "/footballgame/index.html");//Football.html //跳转到我们的游戏界面  足球小将

        }else{
            logger.info("校验错误!");
            response.sendRedirect("http://git.oschina.net");//非法登录
        }
    }


    /**
     * 手机号码登录游戏
     * @param mobilePhone
     * @param password
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "mobileloginGame",method = RequestMethod.POST)
    public JSONObject mobileloginGame(@RequestParam long mobilePhone,@RequestParam String password ,HttpServletRequest request,
                          HttpServletResponse response) throws Exception {


        //正则匹配密码为6-12位的数字和字母
        Pattern p1 = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$");
        Matcher m1 = p1.matcher(password);

        if (!m1.matches()){
            return JSONUtils.getRoot(3,"faild","密码格式错误（6-12位的字母加数字）");
        }

        if (!PhoneFormatCheckUtils.isChinaPhoneLegal(String.valueOf(mobilePhone))){
            return JSONUtils.getRoot(2,"faild","手机号码格式错误");
        }


        password = password + StaticValue.SIGN_KEY;//正确的明文
        password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));//第一次md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));//第二次md5加密
        logger.info("===手机密码加密后==="+password);

        List<FBUserMobile> fbUserMobileList = iUserService.queryUserByMobilePhoneAndPassword(mobilePhone,password);

        if (fbUserMobileList.size()==0||fbUserMobileList.isEmpty()||fbUserMobileList==null){
//            response.sendRedirect("http://"+iDomainService.getDoamin().get(0).getDomainUrl() + "/login.html");//Football.html //跳转到我们的游戏界面  足球小将
            return JSONUtils.getRoot(1,"faild","用户不存在或密码错误");
        }
        else{

            User user = iUserService.getByOpenId(fbUserMobileList.get(0).getOpenid());
            logger.info("=======  手机号码登录成功的用户昵称："+user.getNickName()+"=======");
            //request.getSession().setAttribute("Football",user.getOpenId());

            //手机登录session
            request.getSession().removeAttribute(FootBall.MOBILE_USER_SESSION);
            request.getSession().setAttribute(FootBall.MOBILE_USER_SESSION, user);//将登录的用户信息注册进session中

            //游戏session
            request.getSession().removeAttribute(FootBall.FOOT_USER_SESSION);
            request.getSession().setAttribute(FootBall.FOOT_USER_SESSION, user);//将登录的用户信息注册进session中

            request.getSession().setMaxInactiveInterval(3600 * 24);
//            session.setMaxInactiveInterval();//设置session存活时间
//            StringBuffer url = request.getRequestURL();
//            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append
//                    (request.getServletContext().getContextPath()).append("/").toString();
//            response.sendRedirect(tempContextUrl + "footballgame/index.html");//Football.html //跳转到我们的游戏界面  足球小将
//            response.sendRedirect("http://"+iDomainService.getDoamin().get(0).getDomainUrl() + "/footballgame/index.html");//Football.html //跳转到我们的游戏界面  足球小将
            return JSONUtils.getRoot(0,"success","ok");
//            return null;
        }

    }

    /**
     * 修改绑定的手机号码
     * @return
     */
    @RequestMapping(value = "updateMobilePhone",method = RequestMethod.POST)
    public JSONObject updateMobilePhone(HttpSession session,@RequestParam long mobilePhone,@RequestParam String password){

        //正则匹配密码为6-12位的数字和字母
        Pattern p1 = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$");
        Matcher m1 = p1.matcher(password);

        if (!m1.matches()){
            return JSONUtils.getRoot(4,"faild","密码格式错误（6-12位的字母加数字）");
        }

        if (!PhoneFormatCheckUtils.isChinaPhoneLegal(String.valueOf(mobilePhone))){
            return JSONUtils.getRoot(2,"faild","手机号码格式错误");
        }
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openId=user.getOpenId();
        List<FBUserMobile> fbUserMobileList =  iUserService.queryMobilePhoneByOpenid(openId);

        List<FBUserMobile> fbUserMobileList1 = iUserService.queryMobilePhoneByMobilePhone(mobilePhone);
        if (!fbUserMobileList1.isEmpty()){

            for (int i = 0;i<fbUserMobileList1.size() ;i++){
                if (mobilePhone==fbUserMobileList1.get(i).getMobilePhone() && !openId.equals(fbUserMobileList1.get(i).getOpenid())){
                    return  JSONUtils.getRoot(3,"success","手机号码已被绑定！如需找回手机，可联系客服！");
                }
            }
        }

        if(fbUserMobileList.isEmpty()){
            FBUserMobile fbUserMobile = new FBUserMobile();
            fbUserMobile.setMobilePhone(mobilePhone);
            fbUserMobile.setOpenid(user.getOpenId());
            fbUserMobile.setCreateTime(new Timestamp(new Date().getTime()));

            password = password + StaticValue.SIGN_KEY;//正确的明文
            try {

                password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));//第一次md5加密
                password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));//第二次md5加密

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            logger.info("===手机密码添加之前加密为==="+password);
            fbUserMobile.setPassword(password);

        }else{

            fbUserMobileList.get(0).setMobilePhone(mobilePhone);
            password = password + StaticValue.SIGN_KEY;//正确的明文
            try {

                password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));//第一次md5加密
                password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));//第二次md5加密

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            logger.info("===手机密码添加之前加密为==="+password);
            fbUserMobileList.get(0).setPassword(password);

        }

        boolean boo =  iUserService.updateMobilePhone(fbUserMobileList.get(0));

        if (boo){
            return JSONUtils.getRoot(0,"success","修改成功！");
        }

        return JSONUtils.getRoot(1,"faild","失败");

    }

    /**
     * 根据openid查询记录
     * @return
     */
    @RequestMapping(value = "queryMobilePhoneByOpenid",method = RequestMethod.GET)
    public JSONObject queryMobilePhoneByOpenid(HttpServletRequest request) {

        User user=(User)request.getSession().getAttribute(FootBall.FOOT_USER_SESSION);
        String openId=user.getOpenId();
        List<FBUserMobile> fbUserMobileList =  iUserService.queryMobilePhoneByOpenid(openId);

        if (fbUserMobileList.isEmpty()||fbUserMobileList==null){

            return JSONUtils.getRoot(1,"NO MOBILE_PHONE","未绑定手机号码！");

        }else{

            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("id",fbUserMobileList.get(0).getId());
            jsonObject.put("mobilePhone",fbUserMobileList.get(0).getMobilePhone());
//            jsonObject.put("openid",fbUserMobileList.get(0).getOpenid());
            jsonObject.put("createTime",fbUserMobileList.get(0).getCreateTime());
            return JSONUtils.getRoot(0,"SUCCESS",jsonObject);

        }
    }

    /**
     * 用户的用户详情
     *
     * @return
     */
    @RequestMapping(value = "getUserOpenId")
    public JSONObject selectUserByOpnId(HttpSession session){
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
       String openId=user.getOpenId();
        JSONObject jsonObject=iUserService.selectUserByOpnId(openId);
        return JSONUtils.getRoot(0,"success",jsonObject);
    }

    /**
     * 获取用户信息
     * @param session
     * @return
     */
    @RequestMapping(value = "getUserMessage")
    public JSONObject getUserMessage(HttpSession session){

        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openId=user.getOpenId();
      return JSONUtils.getRoot(0,"success", iUserService.getUserMessage(openId)) ;
    }
    /**
     * 获取用户的支出记录
     * @return
     */
    @RequestMapping(value = "getExpendRecord")
     public JSONObject getExpendRecord(HttpSession session){

        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openId=user.getOpenId();

     JSONObject jsonObject=  iMoneyService.getExpendRecord(openId);
        if(jsonObject==null)
            return JSONUtils.getRoot(1,"fail","该用户没有支出记录");
        return JSONUtils.getRoot(0,"success",jsonObject);
     }

    /**
     * 获取用户的佣金记录
     * @param session
     * @return
     */
     @RequestMapping(value = "getCommissionRecord")
     public JSONObject getCommissionRecord(HttpSession session){
         User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
                  String openId=user.getOpenId();

         JSONObject jsonObject=   iMoneyService.getCommRecord(openId,0);
         if(jsonObject==null)
             return JSONUtils.getRoot(1,"fail","该用户没有佣金记录");
         return JSONUtils.getRoot(0,"success",jsonObject);

     }
    /**
     * 获取代理客服图片
     * @param session
     * @return
     */
    @RequestMapping(value = "getAgentImage")
    public JSONObject getAgentImg(HttpSession session){
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);

        if(user.getProxyId()==1){
            return JSONUtils.getRoot(1,"fail",null);
        }
        AgentImage agentImage= iAgentService.getAgentImage(user.getProxyId());
         if(agentImage!=null)
             return JSONUtils.getRoot(0,"success",agentImage);
        return JSONUtils.getRoot(1,"fail",null);
    }


    /**
     * 添加用户的踢球记录
     * @param betAmount  用户下注的金额
     * @return
     */
    @RequestMapping(value = "setKickBallRecord",method = RequestMethod.POST)
    public synchronized JSONObject setKicBall(@RequestParam double betAmount,@RequestParam double odds,HttpSession session,HttpServletResponse response){
        //下注金额不能大于用户广告金余额
        //判断下注金额是多少
        double num=0;
        double money=0;

        logger.info(odds+"********************************* odds *****************************************");
        if (odds > 100 || odds < 0){
            return null;
        }
        try{


        FbFootGame fbFootGame=  iAdminUserService.getFbFootGame(1);
        if(betAmount==1){
            num=odds * fbFootGame.getProportion()/100;
//            num=odds * FootBall.FIVE_RADIO/100;
            money=1;
        }else if(betAmount==2){
            fbFootGame=  iAdminUserService.getFbFootGame(2);
            num=odds * fbFootGame.getProportion()/100;
//            num=odds * FootBall.TEN_RADIO/100;
            money=10;
        }else if(betAmount==3){
            fbFootGame=  iAdminUserService.getFbFootGame(3);
            num=odds * fbFootGame.getProportion()/100;
//            num=odds * FootBall.FIFTY_RADIO/100;
            money=50;
        }else{
            try {
                response.sendRedirect("http://www.xsrkej.com/");
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //中球几率 ， 赔率
        Random random=new Random();
        int index=random.nextInt(FootBall.FootRatio.length-1);
        double amountMoney=0.0;
        int zq =1;//
        if(index<num){//中球
            fbFootGame=  iAdminUserService.getFbFootGame(4);
            amountMoney = money *fbFootGame.getProportion();//获得中球奖金t
//            amountMoney = money * FootBall.odds;//获得中球奖金t
            zq=0;
        }else{//未中球
            fbFootGame=  iAdminUserService.getFbFootGame(5);
            amountMoney=fbFootGame.getProportion()* money;//获得安慰金
        }
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openId=user.getOpenId();

        Timestamp time = new Timestamp(new Date().getTime());
        JSONObject jsonObject = iUserService.addKicKBall(new KicKBall(openId,time,amountMoney,money));

       int code= (int) jsonObject.get("code");
        if(code==1){
            return  JSONUtils.getRoot(2,"fail","用户余额不足");
        }

        return  JSONUtils.getRoot(zq,"success",jsonObject);//返回踢球所获金额
        }catch(NullPointerException e){
            return  JSONUtils.getRoot(2,"fail","请求错误");
        }
    }

    /**
     * 点击邮箱增加用户赠送广告金
     * @param session
     * @return
     */
    @RequestMapping(value = "setGitMoney",method = RequestMethod.POST)
    public JSONObject setGitMoney(@RequestParam long id,HttpSession session){
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
                String openId=user.getOpenId();

        //将未领取的赠送广告金状态修改为1
        //赠送金额添加到赠送广告金记录表中
       boolean bool= iUserService.setUserGitMoney(openId,id);

        if(bool)
            return JSONUtils.getRoot(0,"success","获取赠送广告金成功");
        return JSONUtils.getRoot(1,"fail","获取赠送广告金失败");
    }

    /**
     * 获取轮播图信息
     * @return
     */
    @RequestMapping(value = "getCarouselFigure")
    @ResponseBody
    public JSONObject getCarouselFigure(){
        logger.info("===================getCarouselFigure=====================");
        return JSONUtils.getRoot(0,"success",iAdminUserService.getAllCarouselFigure());
    }


    /**
     * 获取用户的代理数量
     * @return
     */
    @RequestMapping(value = "getProxyUser")
    public JSONObject getProxyUser(HttpSession session){
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        long uid=user.getId();
      JSONObject jsonObject=  iUserService.getProxyNum(uid);
            return JSONUtils.getRoot(0,"success",jsonObject);
    }


    public User getUser(HttpSession session){
        User user=null;
        try{
            user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
            return user;
        }catch (NullPointerException e){
            return null;
        }

    }

    
    //用户提取佣金
//    @RequestMapping(value = "getCashComm")
    public JSONObject getCashComm(HttpSession session,double money){
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openId=user.getOpenId();
        boolean bool=  iUserService.cash(openId,money);
        if(bool)
            return JSONUtils.getRoot(0,"success","提现成功");
        return JSONUtils.getRoot(1,"fail","提现失败");
    }


    /**
     * 游戏币支付回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/weixinpay/callback",method = RequestMethod.POST)
    public String callBack(HttpServletRequest request){
        logger.info("********************************   游戏币支付回调    *********************************");
        InputStream is = null;
        try {
            is = request.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String xml = inputStream2String(is, "UTF-8");
        logger.info(xml);
        Map<String,String> map  = XMLBeanUtils.readStringXmlOut(xml);
        String resultCode = map.get("result_code");
        String returnCode = map.get("return_code");
        String openid = map.get("openid");
        String cashFee = map.get("cash_fee");
        logger.info("==resultCode=="+resultCode + "==returnCode=="+ returnCode +"==openid==" + openid + "==cashFee=="+cashFee);
        int gitMoney = 0;
        switch(cashFee)

        {

            case "500":

                gitMoney = 1;

                break;

            case "1000":

                gitMoney = 2;

                break;

            case "5000":

                gitMoney = 5;

                break;

            case "50000":

                gitMoney = 50;

                break;

            case "100000":

                gitMoney = 100;

                break;

            case "200000":

                gitMoney = 200;

                break;

            default:

                gitMoney = 0;

                break;

        }
        if("SUCCESS".equals(resultCode) && "SUCCESS".equals(returnCode)){

            setBalanceMoney(openid, Double.parseDouble(cashFee)/100,gitMoney);

        }



        /**
         * 后面把xml转成Map根据数据作逻辑处理
         */
        return xml;
    }


    /**
     * 订单支付回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/weixinpay/ordercallback",method = RequestMethod.POST)
    public String ordercallback(HttpServletRequest request){
        logger.info("********************************   订单支付回调    *********************************");
        InputStream is = null;
        try {
            is = request.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String xml = inputStream2String(is, "UTF-8");
        logger.info(xml);
        Map<String,String> map  = XMLBeanUtils.readStringXmlOut(xml);
        String resultCode = map.get("result_code");
        String returnCode = map.get("return_code");
        String openid = map.get("openid");
        String cashFee = map.get("cash_fee");
        String is_subscribe =  map.get("is_subscribe");
        String transaction_id =  map.get("transaction_id");
        String sign =  map.get("sign");
        String time_end =  map.get("time_end");
        String bank_type =  map.get("bank_type");
        String out_trade_no =  map.get("out_trade_no");

        logger.info("==resultCode=="+resultCode + "==returnCode=="+ returnCode +"==openid==" + openid + "==cashFee=="+cashFee);
        if("SUCCESS".equals(resultCode) && "SUCCESS".equals(returnCode)){


            //系统数据库处理逻辑（）
            FbOrder fbOrder = iMissionService.getOrderByOutTrantId(out_trade_no);
            fbOrder.setPaymentStatus(0);
            boolean boo = iMissionService.updateOrder(fbOrder);

            logger.info("===========更新订单支付状态=="+boo+"========");
//            setBalanceMoney(openid, Double.parseDouble(cashFee)/100,gitMoney);

        }
        /**
         * 后面把xml转成Map根据数据作逻辑处理
         */
        return xml;
    }

    /**
     * InputStream流转换成String字符串
     * @param inStream InputStream流
     * @param encoding 编码格式
     * @return String字符串
     */
    public static String inputStream2String(InputStream inStream, String encoding){
        String result = null;
        try {
            if(inStream != null){
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] tempBytes = new byte[1024000];
                int count = -1;
                while((count = inStream.read(tempBytes, 0, 1024000)) != -1){
                    outStream.write(tempBytes, 0, count);
                }
                tempBytes = null;
                outStream.flush();
                result = new String(outStream.toByteArray(), encoding);
            }
        } catch (Exception e) {
            result = null;
        }
        return result;
    }

    //用户充值广告金
    public void setBalanceMoney(String openid,double money,double gitMoney){

        logger.info("money==="+money+"===gitMoney======"+gitMoney);
        String openId=openid;//前端测试
        logger.info("openId==="+openId);
       boolean bool= iUserService.rechargeRecord(openId,money);
        logger.info(bool + "充值成功！*************************");
        if(bool){
            //充值成功赠送广告金   如果是第一次充值就赠送广告金
           JSONObject jsonObject= iUserService.setGitMoney(openId,gitMoney,money);
            boolean boo= (boolean) jsonObject.get("bool");
           if(boo){
               jsonObject.put("vlaue","首次充值成功，获得赠送广告金");
           }
            jsonObject.put("vlaue","充值成功");
        }
    }


    /**
     * 获取版本信息
     * @return
     */
    @RequestMapping(value = "getEdition")
    public JSONObject getEdition(){

        return iUserService.getEditionInfo();
    }

    /**
     * 获取系统设置信息
     * @return
     */
    @RequestMapping(value = "getSystemSetting")
    public JSONObject getSystemSetting(){

        JSONObject jsonObject=  iAdminUserService.getSystemSetting();
        if(jsonObject!=null)
            return  JSONUtils.getRoot(0,"success",jsonObject);
        return JSONUtils.getRoot(1,"fail",null);
    }

    /**
     * 获取常见问题
     * @return
     */
    @RequestMapping(value = "getCommonProblem")
    public JSONObject getCommonProblem(){

        JSONObject jsonObject=  iAdminUserService.getCommonProblem();
        if(jsonObject==null)
            return JSONUtils.getRoot(1,"fail",null);
        return JSONUtils.getRoot(0,"success",jsonObject);
    }
    /**
     * 生成二维码
     * @param session
     * @return
     */
    @RequestMapping(value = "getQRCode")
    public JSONObject getSubLevelCommission(HttpSession session) {
        User userDO = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        userDO=iUserService.getUserByUid(userDO.getId());
//        String openId=userDO.getOpenId();//前端测试
        //userDO=iUserService.getUserByUid(2);
        return JSONUtils.getRoot(SUCCESS, "success", userDO.getQrCode());
    }


    /**
     * 设置使用支付宝提现佣金
     * @param session
     * @param aliPayAccount
     * @return
     */
    @RequestMapping(value = "setAliPay",method = RequestMethod.GET)
    public JSONObject setAliPay(HttpSession session, @RequestParam String aliPayAccount){

        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String openId=user.getOpenId();
        AliPayCashRecord aliPayCashRecord=new AliPayCashRecord(openId,aliPayAccount,1,"审核中");

        AliPayCashRecord aliPayCashRecord1= iMoneyService.saveAliPay(aliPayCashRecord);
        if(aliPayCashRecord1!=null)
            return JSONUtils.getRoot(0,"success",null);

        return JSONUtils.getRoot(1,"fail",null);
    }

    //用户个人空间  说说
    @RequestMapping(value = "saveUserMood" ,method = RequestMethod.PUT)
    @ResponseBody
    public JSONObject saveUserMood(HttpSession session,HttpServletRequest request,@RequestParam String conntent,@RequestParam(value = "headImg[]",required = false,defaultValue = "") String[] headImg){

        logger.info("================   说说进入  ===================");
//        logger.info(conntent);
//        logger.info(headImg[0]);
        if("".equals(conntent) || conntent==null || headImg.length==0  || headImg.length>3){
            return JSONUtils.getRoot(1,"faild","参数不能为空");
        }

        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);
//        String openId=user.getOpenId();
        String[] imgUrl=new String[headImg.length];
        String path="userMood/";
        String uploadDir= request.getSession().getServletContext().getRealPath("/");
//        logger.info(headImg[1]+".............................urlLength");
        for (int i=0;i<headImg.length;i++) {
            imgUrl[i]= UploadUtils.upload(request,headImg[i],path);
            logger.info("说说图片的路径==================="+imgUrl[i]);
        }

//        Timestamp createTime, String conntent, String userHeadimg, String userName, String contentImg, String userOpenid
        FbUsermood usermood=new FbUsermood();
        usermood.setCreateTime(new Timestamp(new Date().getTime()));
        usermood.setConntent(conntent);
        usermood.setUserHeadimg(user.getHeadImgUrl());
        usermood.setUserName(user.getNickName());
        usermood.setUserOpenid(user.getOpenId());
        usermood.setContentImg(imgUrl[0]);

        List<FbMoodImg> fbMoodImgList =new ArrayList<FbMoodImg>();
        for(int i=0;i<imgUrl.length;i++){
            //String imgPath, Long imgSize, Timestamp createTime, String userName, String userHeadimg
            File file=new File(uploadDir+imgUrl[i]);

            FbMoodImg fbMoodImg=new FbMoodImg(imgUrl[i],file.length(),usermood.getCreateTime(),usermood.getUserName(),usermood.getUserHeadimg());
            fbMoodImgList.add(fbMoodImg);
        }
        JSONObject jsonObject=iUserService.saveUserMood(usermood,fbMoodImgList);
       int code= (int) jsonObject.get("error_code");
       if(code==0){
           //判断是否领取任务
           UploadUtils.missionUtil(user,2,iMissionService);
       }
        return   jsonObject;
//        return   null;
    }


    @RequestMapping(value = "getFbUserMoodById" ,method = RequestMethod.GET)
    public JSONObject getFbUserMoodById(@RequestParam long id){


        FbUsermood fbUsermood = iUserService.getFbUserMoodById(id);
        JSONObject jsonObject=new JSONObject();

        if(fbUsermood!=null){
            List<FbMoodImg> fbMoodImgList =   iUserService.selectFbMoodImgsByMoodId(id);
            JSONArray jsonArray=new JSONArray();
            for (FbMoodImg fb:fbMoodImgList) {
                JSONObject object=new JSONObject();
                object.put("imgPath",fb.getImgPath());
                object.put("imgSize",fb.getImgSize());
                jsonArray.add(object);
            }

            jsonObject.put("id",fbUsermood.getId());
            jsonObject.put("conntent",fbUsermood.getConntent());
            jsonObject.put("createTime",fbUsermood.getCreateTime());
            jsonObject.put("userName",fbUsermood.getUserName());
            jsonObject.put("headImgUrl",fbUsermood.getUserHeadimg());
            jsonObject.put("openid",fbUsermood.getUserOpenid());
            jsonObject.put("imgUrlValue",jsonArray);
        }
       if(jsonObject!=null)
           return JSONUtils.getRoot(0,"success",jsonObject);
        return JSONUtils.getRoot(1,"faild",null);
    }


    @RequestMapping(value = "selectUsermoods" ,method = RequestMethod.GET)
    public JSONObject selectUsermoods(HttpSession session,@RequestParam int startPage){
        User user=(User)session.getAttribute(FootBall.FOOT_USER_SESSION);

        String openId=user.getOpenId();
        JSONObject object=new JSONObject();
        object.put("userName", user.getNickName());
        object.put("headImgUrl", user.getHeadImgUrl());
        object.put("openid", openId);
        object.put("value","");
        List list = iUserService.selectUsermoods(openId,startPage);
        if(list!=null) {
            if(startPage >(int)list.get(1)){
                return JSONUtils.getRoot(0,"success",object);
            }
            JSONArray jsonArray = new JSONArray();

            for (FbUsermood fbUsermood :(List<FbUsermood>) list.get(0)) {
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("id", fbUsermood.getId());
                jsonObject.put("conntent", fbUsermood.getConntent());
                jsonObject.put("createTime", fbUsermood.getCreateTime());
                jsonObject.put("contentImg",fbUsermood.getContentImg());
                jsonArray.add(jsonObject);
            }
            object.put("value",jsonArray);
            object.put("totalPage",list.get(1));
            object.put("inPage",list.get(2));
        }

        if(object!=null)
            return JSONUtils.getRoot(0,"success",object);

        return JSONUtils.getRoot(1,"faild",null);
    }

    /**
     * 个人主页
     * @param session
     * @param startPage
     * @return
     */
    @RequestMapping(value = "selectUsermoodsByOpenid" ,method = RequestMethod.GET)
    public JSONObject selectUsermoodsByOpenid(HttpSession session,@RequestParam int startPage,@RequestParam String openid){
        JSONObject object=new JSONObject();
        Object[] obj = iUserService.getNickName(openid);
        if(obj!=null){
            object.put("nickName",obj[0]);//获得用户昵称
            object.put("headImgurl",obj[1]);//用户头像
        }
        object.put("openid", openid);
        object.put("value","");
        List list = iUserService.selectUsermoods(openid,startPage);
        if(list!=null) {
            if(startPage > (int)list.get(1)){
                return JSONUtils.getRoot(0,"success",object);
            }
            JSONArray jsonArray = new JSONArray();
            for (FbUsermood fbUsermood :(List<FbUsermood>) list.get(0)) {
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("id", fbUsermood.getId());
                jsonObject.put("conntent", fbUsermood.getConntent());
                jsonObject.put("createTime", fbUsermood.getCreateTime());
                jsonObject.put("contentImg",fbUsermood.getContentImg());
                jsonArray.add(jsonObject);
            }
            object.put("value",jsonArray);
            object.put("totalPage",list.get(1));
            object.put("inPage",list.get(2));
        }

        if(object!=null)
            return JSONUtils.getRoot(0,"success",object);
        return JSONUtils.getRoot(1,"faild",null);
    }





    private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 企业付款

    @RequestMapping(value = "/updateAction",method = RequestMethod.POST)
    @ResponseBody
    public  JSONObject updateAction(HttpServletRequest request,HttpServletResponse response){

//        logger.info("======进入updateAction======"+actionId+"==="+id);
//        if (actionId==2){
//            iWithdrawalService.updateAction(id,actionId);
//            logger.info("提现拒绝");
//            return JSONUtils.getRoot(0, "success", "提现拒绝");
//        }
//        User userDO = iUserService.getUserInfoById(uid);
        //是否关闭微信支付功能
        AliPaySwitch aliPaySwitch = iAdminUserService.getAliPaySwitch();
        if (aliPaySwitch.getStatus()==0){
            return JSONUtils.getRoot(3,"faild","提现时间段为参考公告！");
        }

        JSONObject returnjson = new JSONObject();
        User userDO = (User)request.getSession().getAttribute(FootBall.FOOT_USER_SESSION);

        //拉黑用户检测，并且拒绝其访问
        List<BadUserDO> badUserDOList = iBadUserService.getBadUserByOpenid(userDO.getOpenId());
        if (badUserDOList.size() > 0){
            try {
                response.sendRedirect("http://www.google.com/");
            } catch (IOException e) {
                e.printStackTrace();
            }
            returnjson = JSONUtils.getRoot(1,"faild","账户异常，暂不可提现！");
            return returnjson;
        }


       long count= iCashRegisterDAO.getCountCashRecord(userDO.getOpenId());
       if(count >= 3){
           returnjson = JSONUtils.getRoot(4,"faild","今天提现次数为0！");
           return returnjson;
       }

        int money = 0;
        int upmoney = 0;
        int result=  0;
        synchronized(this)//这个对象可以为任意对象
        {
            //业务判断 openid是否有收款资格
             money = (int) (iMoneyService.getUserCommissionyByOpenId(userDO.getOpenId()).getMoney() * 100);
             //upmoney 是剩余可提现的金额
             upmoney = (int) (iUserService.checkCashMoneyAmount(userDO.getOpenId()) * 100);
             if (upmoney <=0){
                 return JSONUtils.getRoot(2,"faild","今日提现额度已用完，请充值后提高提现额度后再操作");
             }
            double lastmoney = 0.0;
            if(upmoney < money){
                lastmoney = money - upmoney;
                money = upmoney;
            }
             result=  iCommissionFootDAO.changeMoney(userDO.getOpenId(),lastmoney / 100);
        }


        System.out.println(money);
        if (money < 1){
            returnjson = JSONUtils.getRoot(1,"faild","提现金额不能小于1元！");
        }
        if (money >=1 && result ==1){
            logger.info("openid为："+userDO.getOpenId() + "的用户正在提现[/transfer/pay]");

            String partner_trade_no =  PayUtil.getTransferNo();
            String openid = userDO.getOpenId();
            String amount =  String.valueOf(money);
            String spbill_create_ip =  PayUtil.getLocalIp(request);
            Date now = new Date();
            Timestamp create_time = new Timestamp(now.getTime());

            try {
                Map<String, String> parm = new HashMap<String, String>();
                parm.put("mch_appid", StaticValue.WX.AppId); //公众账号appid
                parm.put("mchid", StaticValue.WX.MH_ID); //商户号
                parm.put("nonce_str", PayUtil.getNonceStr()); //随机字符串
                parm.put("partner_trade_no", partner_trade_no); //商户订单号
                parm.put("openid", openid); //用户openid
                parm.put("check_name", "NO_CHECK"); //校验用户姓名选项 OPTION_CHECK
                //parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
                parm.put("amount", amount); //转账金额,单位：分
                parm.put("desc", "转账到个人"); //企业付款描述信息
                parm.put("spbill_create_ip", spbill_create_ip); //服务器Ip地址
                parm.put("sign", PayUtil.getSign(parm, StaticValue.WX.APP_KEY));
                String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));

//                logger.info("restxml:"+restxml);
                Map<String,String> maptemp = XMLBeanUtils.readStringXmlOut(restxml);

                String returnCode = maptemp.get("return_code");
                String resultCode = maptemp.get("result_code");
                String returnMsg = "";
                String errCodeDes = "";
                String errCode = "";
                String paymentNo = "";
                String paymentTime = "";

                logger.info("微信提现返回：");
                logger.info("returnCode=="+returnCode);
                logger.info("resultCode=="+resultCode);
                if("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)){
    //                iWithdrawalService.updateAction(id,actionId);

                    returnMsg = maptemp.get("return_msg");
                    paymentNo = maptemp.get("payment_no");
                    paymentTime = maptemp.get("payment_time");

                    FbWxSuitcaseDO fbWxSuitcaseDO = new FbWxSuitcaseDO();
                    fbWxSuitcaseDO.setOpenid(openid);
                    fbWxSuitcaseDO.setAmount(amount);
                    fbWxSuitcaseDO.setCreateTime(create_time);
                    fbWxSuitcaseDO.setPartnerTradeNo(partner_trade_no);
                    fbWxSuitcaseDO.setPaymentNo(paymentNo);
                    fbWxSuitcaseDO.setPaymentTime(Timestamp.valueOf(paymentTime));
                    fbWxSuitcaseDO.setReturnMsg(returnMsg);
                    fbWxSuitcaseDO.setResultCode(resultCode);
                    fbWxSuitcaseDO.setReturnCode(returnCode);
                    fbWxSuitcaseDO.setSpbillCreateIp(spbill_create_ip);
//                    iFbWxSuitcaseDAO.save(fbWxSuitcaseDO);
                    iFbWxSuitcaseService.save(fbWxSuitcaseDO);
//                    String m = money + "";
//                    Double d1 = Double.parseDouble(m)/100;
                    Double d2 = Double.parseDouble(String.valueOf(money))/100;
                    //调用系统提现逻辑
                    getCashComm(request.getSession(),d2);
                    logger.info("提现申请成功，提现金额为：" + d2);
                    returnjson =  JSONUtils.getRoot(0, "success", "提现申请成功");
                }else{
                     returnMsg = maptemp.get("return_msg");
                     errCodeDes = maptemp.get("err_code_des");
                     errCode = maptemp.get("err_code");

                    FbWxSuitcaseDO fbWxSuitcaseDO = new FbWxSuitcaseDO();
                    fbWxSuitcaseDO.setOpenid(openid);
                    fbWxSuitcaseDO.setAmount(amount);
                    fbWxSuitcaseDO.setCreateTime(create_time);
                    fbWxSuitcaseDO.setPartnerTradeNo(partner_trade_no);
                    fbWxSuitcaseDO.setPaymentNo(paymentNo);
                    fbWxSuitcaseDO.setPaymentTime(Timestamp.valueOf(paymentTime));
                    fbWxSuitcaseDO.setReturnMsg(returnMsg);
                    fbWxSuitcaseDO.setResultCode(resultCode);
                    fbWxSuitcaseDO.setReturnCode(returnCode);
                    fbWxSuitcaseDO.setSpbillCreateIp(spbill_create_ip);
                    fbWxSuitcaseDO.setErrCode(errCode);
                    fbWxSuitcaseDO.setErrCodeDes(errCodeDes);
//                    iFbWxSuitcaseDAO.save(fbWxSuitcaseDO);
                    iFbWxSuitcaseService.save(fbWxSuitcaseDO);

                    logger.info("提现申请失败");
                    returnjson =   JSONUtils.getRoot(-1,"faild",errCodeDes);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                returnjson =   JSONUtils.getRoot(-1,"faild",e.getMessage());
            }
        }
        return returnjson;
    }

    /**
     * 添加评论
     * @param session
     * @param content
     * @param moodId
     * @return
     */
    @RequestMapping(value = "saveComment",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveComment(HttpSession session, @RequestParam String content,@RequestParam Long moodId){

        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);

        if (content==null || moodId==null || moodId <= 0 || content.length() > 500){
            return JSONUtils.getRoot(1,"faild","参数格式错误！");
        }

        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }

        FbComment fbComment = new FbComment();
        fbComment.setContent(content);
        fbComment.setMoodId(moodId);
        fbComment.setUserHeadimg(user.getHeadImgUrl());
        fbComment.setUserName(user.getNickName());
        fbComment.setUserOpenid(user.getOpenId());
//        fbComment.setUserHeadimg("http://wx.qlogo.cn/mmopen/icPlfYJIDPMyFbsWaW5KocoSQY4EROy5Ce6LIKrhdacjmiapTDRv79g99s1oYc3szKVx1kADIYjvQJwlLWxlDrXfB2ySQjeLPf/0");
//        fbComment.setUserName("小星星");
//        fbComment.setUserOpenid("oyGuGwu-Avfv6SYRrzCV5wzDcDa8");

        fbComment.setCreateTime(new Timestamp(new Date().getTime()));

        try {

            iUserService.saveComment(fbComment);
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("nickName",user.getNickName());
            jsonObject.put("content",content);
            jsonObject.put("openId",user.getOpenId());
            return  JSONUtils.getRoot(0,"success",jsonObject);

        }catch (Exception E){
            return JSONUtils.getRoot(1,"faild",E.getMessage());
        }
    }


    /**
     * 查询评论
     * @param session
     * @param moodId
     * @return
     */
    @RequestMapping(value = "selectCommentsByMoodId",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject selectCommentsByMoodId(HttpSession session,@RequestParam Long moodId){

        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);

        if (moodId==null || moodId <= 0){
            return JSONUtils.getRoot(1,"faild","参数格式错误！");
        }

        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }

        try {
            List<FbComment> fbCommentsList = iUserService.selectCommentsByMoodId(moodId);

            JSONArray jarr = new JSONArray();
            for (int i =0 ;i<fbCommentsList.size();i++){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",fbCommentsList.get(i).getId());
                jsonObject.put("content",fbCommentsList.get(i).getContent());
                jsonObject.put("createTime",fbCommentsList.get(i).getCreateTime());
                jsonObject.put("userName",fbCommentsList.get(i).getUserName());
                jsonObject.put("userHeadimg",fbCommentsList.get(i).getUserHeadimg());
                jsonObject.put("userOpenid",fbCommentsList.get(i).getUserOpenid());
                jsonObject.put("moodId",fbCommentsList.get(i).getMoodId());
                jarr.add(jsonObject);
            }

            return  JSONUtils.getRoot(0,"success",jarr);
        }catch (Exception e){
            return  JSONUtils.getRoot(1,"faild",e.getMessage());
        }

    }

    //查询当天的任务
    @RequestMapping(value = "getMissionRecordNow")
    public JSONObject getMissionRecordNow(HttpSession session){
        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }

        String openId=user.getOpenId();
        JSONArray jsonArray= iMissionService.getMissionRecordNow(openId);
        if(jsonArray!=null){
            logger.info("missionRecord.size======================"+jsonArray.size());

            return JSONUtils.getRoot(0,"success",jsonArray);
        }
        return JSONUtils.getRoot(1,"faild","");
    }


    /**
     * 用户领取每日任务
     * @return
     */
    @RequestMapping(value = "getMission")
    public JSONObject getMission(HttpSession session,@RequestParam long missionId){
        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
        if(missionId < 0 ){
            return JSONUtils.getRoot(1,"faild","参数有误");
        }

        FbUserMission userMission=new FbUserMission();
        userMission.setUid(user.getId());
        userMission.setOpenId(user.getOpenId());
        userMission.setNickName(user.getNickName());
        userMission.setHeadImgUrl(user.getHeadImgUrl());
//        userMission.setUid(1L);
//        userMission.setHeadImgUrl("http://wx.qlogo.cn/mmopen/icPlfYJIDPMyFbsWaW5KocoSQY4EROy5Ce6LIKrhdacjmiapTDRv79g99s1oYc3szKVx1kADIYjvQJwlLWxlDrXfB2ySQjeLPf/0");
//        userMission.setNickName("小星星");
//        userMission.setOpenId("oyGuGwu-Avfv6SYRrzCV5wzDcDa8");
        userMission.setMissionId(missionId);
        userMission.setCreateTime(new Timestamp(new Date().getTime()));
        userMission.setStatus(1);//领取
        int  result= iMissionService.saveUserMission(userMission);

        logger.info("领取任务的状态=================="+result);
        if(result==0){
            return JSONUtils.getRoot(0,"success","领取成功");
        }
        return JSONUtils.getRoot(result,"fails","领取失败");
    }

    /**
     * 转动转盘获取奖励
     * @return
     */
    @RequestMapping(value = "getTurntableRecord")
    public JSONObject getTurntableRecord(HttpSession session){
//        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
        List<FbTurntableRecord> list=iMissionService.getFbTurntableRecord(user.getId());
        try{
        if(list.size()>0){
            //修改用户奖励已领取
            FbTurntableRecord turntableRecord=list.get(0);
            turntableRecord.setStatus(1);//用户奖励已领取
            boolean bool=  iMissionService.updateTurntableRecord(turntableRecord);
              if(bool) {//修改成功后返回
                  int status=0;
                  if(turntableRecord.getAwardId()==6){//谢谢惠顾，直接设置已领取
                      status=1;
                  }
//                  String nickName, String openId, long uid, String headImgUrl, long missionId, String missionContent, long awardId, String awardContent, Timestamp createTime, int status
                 FbUserAwardRecord userAwardRecord=new FbUserAwardRecord(user.getNickName(),user.getOpenId(),user.getId(),user.getHeadImgUrl(),turntableRecord.getMissionId(),
                         turntableRecord.getMissionContent(),turntableRecord.getAwardId(), turntableRecord.getAwardContent(),new Timestamp(new Date().getTime()),status);

                  FbUserAwardRecord fbUserAwardRecord=  iMissionService.saveUserAwardRecord(userAwardRecord);
                  return JSONUtils.getRoot(0, "success", fbUserAwardRecord);
              }
        }
        }catch (NullPointerException e){
            return JSONUtils.getRoot(1,"faild","用户异常，请稍后重试");
        }
        return JSONUtils.getRoot(1,"faild","暂无抽奖机会，请完成任务后进行抽奖");
    }

    //领取奖励
    @RequestMapping(value = "getUserAward")
    public JSONObject getUserAward(HttpSession session,@RequestParam long id) {

        if("".equals(id) || id<=0){
            return JSONUtils.getRoot(1,"faild","参数有误");
        }
//        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }

        FbUserAwardRecord userAwardRecord= iMissionService.getUserAwardByAwardId(id,user.getOpenId());
        if(userAwardRecord ==null){
            return JSONUtils.getRoot(1,"faild","用户该条奖励记录不存在");
        }

        if(userAwardRecord.getStatus()==1){
            return JSONUtils.getRoot(1,"faild","用户该条奖励已领取");
        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("count", iMissionService.getTurntableRecordCount(user.getOpenId()));

        //修改奖励状态
        userAwardRecord.setStatus(1);
            //再来一次
            if(userAwardRecord.getAwardId()==5){
                //获取可领取的奖励
                List<FbMissionAward> missionAwards = iMissionService.getMissionAwardStatus();
                if(missionAwards!=null) {
                    Random random = new Random();
                    int result = random.nextInt(missionAwards.size());
                    FbMissionAward missionAward = missionAwards.get(result);  //获取奖励信息
                    //重新添加转盘记录
                    //String nickName, String openId, long uid, String headImgUrl, long missionId, String missionContent, long awardId, String awardContent, int status
                    FbTurntableRecord fbTurntableRecord=new FbTurntableRecord(user.getNickName(),user.getOpenId(),user.getId(),user.getHeadImgUrl(),6,
                            "转盘奖励，再来一次",missionAward.getId(),missionAward.getAwardContent(),0,new Timestamp(new Date().getTime()));

                    FbTurntableRecord record = iMissionService.saveFbTurntableRecord(fbTurntableRecord);
                    if(record!=null){
                        boolean bool=   iMissionService.updateUserAwardRecord(userAwardRecord);
                        if(bool) {
                            jsonObject.put("count", iMissionService.getTurntableRecordCount(user.getOpenId()));
                            return JSONUtils.getRoot(0, "success", jsonObject);
                        }

                    }
                }
            }

            if( userAwardRecord.getAwardId()<5  ) {
                CommissionRecord commissionRecord = new CommissionRecord();
                commissionRecord.setOpenId(user.getOpenId());
                commissionRecord.setCommissionTime(new Timestamp(new Date().getTime()));
                commissionRecord.setCommissionType("任务");
                //奖励为1,2,3,4时增加用户余额
                if (userAwardRecord.getAwardId() == 1) {
                    updateComm(commissionRecord, user.getOpenId(), 1);
                }

                if (userAwardRecord.getAwardId() == 2) {
                    updateComm(commissionRecord, user.getOpenId(), 2);
                }

                if (userAwardRecord.getAwardId() == 3) {
                    updateComm(commissionRecord, user.getOpenId(), 3);
                }

                if (userAwardRecord.getAwardId() == 4) {
                    updateComm(commissionRecord, user.getOpenId(), 6);
                }
                boolean bool=   iMissionService.updateUserAwardRecord(userAwardRecord);
                if(bool) {
                    return JSONUtils.getRoot(0, "success", jsonObject);
                }

            }

            if(userAwardRecord.getAwardId() > 6 && userAwardRecord.getAwardId() <= 10 ){
                //奖品详情页
                FbAwardDetails awardDetails=iMissionService.getAwardDetailsByAwardId(userAwardRecord.getAwardId());
                if(awardDetails!=null){
                    jsonObject.put("value",awardDetails);
                    return JSONUtils.getRoot(0, "success", jsonObject);
                }
            }


          return JSONUtils.getRoot(1,"faild","领取失败，请稍后重试");
        }


    public void updateComm(CommissionRecord commissionRecord,String openId,double money){
        iMoneyService.updateCommission(openId,money);
        //增加佣金记录
        commissionRecord.setCommissionMoney(money);
        iMoneyService.saveCommissionRecord(commissionRecord);

    }

    //查询奖品的订单信息
    @RequestMapping(value = "getAwardOrder")
    public JSONObject getAwardOrder(HttpSession session,@RequestParam long id,@RequestParam long awardId,@RequestParam long addressId){
        logger.info("地址id1111111111========================="+addressId+"id1111111111"+id+"awardId============"+awardId);
        if(id < 0 || awardId < 7 || awardId > 10 || addressId<0){
            return JSONUtils.getRoot(1,"faild","参数有误");
        }
//        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
        logger.info("地址id1111111111========================="+addressId);
        FbUserAwardRecord userAwardRecord= iMissionService.getUserAwardByAwardId(id,user.getOpenId());
        logger.info("userAwardRecord========================="+userAwardRecord);
        if(userAwardRecord!=null){
            if(userAwardRecord.getAwardId()==awardId){
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("awardId",userAwardRecord.getAwardId());
                jsonObject.put("awardContent",userAwardRecord.getAwardContent());
                jsonObject.put("id",userAwardRecord.getId());
                logger.info("地址id1111111111========================="+addressId);
                 double money=5;
                if(userAwardRecord.getAwardId()==7){
                        jsonObject.put("awardImg",FootBall.mobilePendant);
                }
                if(userAwardRecord.getAwardId()==8){
                    money=10;//充电宝
                    jsonObject.put("awardImg",FootBall.CDB);
                }
                logger.info("地址id11111151========================="+addressId);
                if(userAwardRecord.getAwardId()==9){
                    jsonObject.put("awardImg",FootBall.appleComputer);
                }
                if(userAwardRecord.getAwardId()==10){
                    jsonObject.put("awardImg",FootBall.iPhone7);
                }
                jsonObject.put("address","");
                logger.info("地址id========================="+addressId);
                if(addressId==0){
                    //获取默认地址
                    FbAddress fbAddress=  iMissionService.getAddressDefault(user.getOpenId());
                    if(fbAddress==null){
                        List<FbAddress> list = iMissionService.getFbAddressAll(user.getOpenId());
                        if(list!=null){
                            jsonObject.put("address",fbAddress);
                        }
                    }else{
                        jsonObject.put("address",fbAddress);
                    }
                }else if(addressId>0){
                    FbAddress  address=  iMissionService.getAddressByOpenId(user.getOpenId(),addressId);
                    if(address!=null){
                        jsonObject.put("address",address);
                    }
                }
                logger.info("地址========================="+jsonObject.get("address"));
                jsonObject.put("money",money);
                return JSONUtils.getRoot(0, "success", jsonObject);
            }else{
                return JSONUtils.getRoot(1,"faild","用户没有该条奖励");
            }


        }
        return JSONUtils.getRoot(1,"faild","");
    }

    //添加地址
    @RequestMapping(value = "saveAddress")
    public JSONObject saveAddress(HttpSession session,@RequestParam String province,@RequestParam String city,@RequestParam String district,@RequestParam String address,
                                  @RequestParam String postCode,@RequestParam String name,@RequestParam String phone){

        if(province==null || "".equals(province) || city==null || "".equals(city)  || district==null || "".equals(district) ||  address==null || "".equals(address)
                ||  postCode==null || "".equals(postCode)||  name==null || "".equals(name) ||  phone==null || "".equals(phone)){
            return JSONUtils.getRoot(1,"faild","参数有误");
        }

        // 匹配中国邮政编码
        //验证成功返回true，验证失败返回false
        String reg = "[1-9]\\d{5}";
            boolean bool=true;
            bool=Pattern.matches(reg, postCode);
            if(! bool){
                return JSONUtils.getRoot(1,"faild","邮编格式有误");
            }

            //验证手机号码
         bool=PhoneFormatCheckUtils.isPhoneLegal(phone);
        if(! bool){
            return JSONUtils.getRoot(1,"faild","手机号码格式有误");
        }

//      User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
        String addres=province+city+district+address;
//        String openId, long uid, String nickName, String headImgUrl, String name, String phone,
//        String province, String city, String district, String address, String postCode, Timestamp createTime, int status
        FbAddress fbAddress= iMissionService.saveFbAddress(new FbAddress(user.getOpenId(),user.getId(),user.getNickName(),user.getHeadImgUrl(),name,phone,
                province,city,district,addres,postCode,new Timestamp(new Date().getTime()),0));

        if(fbAddress!=null){
            return JSONUtils.getRoot(0, "success", fbAddress);
        }
        return JSONUtils.getRoot(1,"faild","设置地址失败，请稍后重试");
    }

    //获取用户所有的地址
    @RequestMapping(value = "getAddressAll")
    public  JSONObject getAddressAll(HttpSession session){

//        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }

        List<FbAddress> list = iMissionService.getFbAddressAll(user.getOpenId());
        if(list!=null){
            return JSONUtils.getRoot(0, "success", list);
        }
        return JSONUtils.getRoot(1,"faild","用户暂未添加地址");
    }

    //修改默认地址
    @RequestMapping(value = "setDefaultAddress")
     public  JSONObject setDefaultAddress(HttpSession session,@RequestParam long addressId){

        if(addressId<0 || "".equals(addressId)){
            return JSONUtils.getRoot(1,"faild","参数有误");
        }
//         User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        User user= getTestUser(session);
         if(user == null){
             return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
         }
        //获取默认地址
        FbAddress fbAddress=  iMissionService.getAddressDefault(user.getOpenId());
            if(fbAddress!=null) {
                fbAddress.setStatus(0);//修改之前的默认地址
                boolean boo = iMissionService.updateFbAddress(fbAddress);
                if(!boo){
                    return JSONUtils.getRoot(1,"faild","修改默认地址失败，请稍后重试！");
                }
            }

        FbAddress address= iMissionService.getAddressByOpenId(user.getOpenId(),addressId);
            if(address!=null){
                //修改用户改地址为默认地址
                address.setStatus(1);
                boolean bool= iMissionService.updateFbAddress(address);
                if(bool){
                    return JSONUtils.getRoot(0, "success", "设置成功");
                }
            }
         return JSONUtils.getRoot(1,"faild","");
     }


     //添加订单
    @RequestMapping(value = "saveOrder")
     public JSONObject saveOrder(HttpSession session,@RequestParam long id,@RequestParam long awardId,@RequestParam long addressId){

        if(id < 0 || awardId < 7 || awardId > 10){
            return JSONUtils.getRoot(1,"faild","参数有误");
        }
//        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
       User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }

        //提交订单修改用户奖励已领取
        FbUserAwardRecord userAwardRecord= iMissionService.getUserAwardByAwardId(id,user.getOpenId());
        userAwardRecord.setStatus(1);
        boolean bool=   iMissionService.updateUserAwardRecord(userAwardRecord);
        if(userAwardRecord!=null) {
            if (userAwardRecord.getAwardId() == awardId) {
                double money=5;
                String awardImg=FootBall.mobilePendant;
                if(userAwardRecord.getAwardId()==7){
                    awardImg=FootBall.mobilePendant;
                }
                if(userAwardRecord.getAwardId()==8){
                    money=10;//充电宝
                    awardImg=FootBall.CDB;
                }
                if(userAwardRecord.getAwardId()==9){
                    awardImg=FootBall.appleComputer;
                }
                if(userAwardRecord.getAwardId()==10){
                    awardImg=FootBall.iPhone7;
                }
                FbAddress address=  iMissionService.getAddressByOpenId(user.getOpenId(),addressId);
                if(address!=null){
//                    String orderId, String openId, long uid, String nickName, String headImgUrl, long userAwardId, long awardId, String awardContent, String awardImgUrl, int status,int paymentStatus,
//                      String expressId, String expressName, Timestamp createTime, long addressId, String address, String name, String phone, double orderMoney
                    FbOrder fbOrder=new FbOrder( WXPayUtil.generateUUID(),user.getOpenId(),user.getId(),user.getNickName(),user.getHeadImgUrl(), id,awardId,userAwardRecord.getAwardContent(), awardImg,1,1,
                            "","",new Timestamp(new Date().getTime()),addressId,address.getAddress(),address.getName(),address.getPhone(),money);
                    FbOrder order=iMissionService.saveFbOrder(fbOrder);
                    if(order!=null){
                        return JSONUtils.getRoot(0, "success", order);
                    }
                }

            }
        }
         return JSONUtils.getRoot(1,"faild","");
     }


    //用户所有奖励信息
    @RequestMapping(value = "getUserAwardRecord")
        public JSONObject getUserAwardRecord(HttpSession session){
            User user= getTestUser(session);
            if(user == null){
                return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
            }
            List<FbUserAwardRecord> list=  iMissionService.getUserAwardRecord(user.getOpenId());
            if(list!=null){
                return JSONUtils.getRoot(0, "success", list);
            }
            return JSONUtils.getRoot(1,"faild","");
        }

    //用户所有订单信息
    @RequestMapping(value = "getUserOrderRecord")
    public JSONObject getUserOrderRecord(HttpSession session){
        User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }

        List<FbOrder> list=  iMissionService.getUserFbOrder(user.getOpenId());
        if(list!=null){
            return JSONUtils.getRoot(0, "success", list);
        }

        return JSONUtils.getRoot(1,"faild","");
    }

    //获取单个订单信息
    @RequestMapping(value = "getOrderByOrderId")
    public JSONObject getOrderByOrderId(HttpSession session,@RequestParam String orderId){

        logger.info("orderId========================"+orderId);
        User user= getTestUser(session);
        if(user == null){
            return JSONUtils.getRoot(1,"faild","用户不存在，重新登录！");
        }
       FbOrder order= iMissionService.getOrderByOutTrantId(orderId);
        if(order!=null){
            return JSONUtils.getRoot(0, "success", order);
        }
        return JSONUtils.getRoot(1,"faild",null);
    }


    public User getTestUser(HttpSession session){
        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
//        User user=iUserService.getUserByUid(1);
        return user;
        }

}












